package com.sdk.util;

import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import org.apache.http.HttpClientConnection;

import android.util.Log;

public class PhoneNumberUtil {
	private static final String YAODAO_PHONE_LOCATION_API = "http://www.youdao.com/smartresult-xml/search.s?type=mobile&q=";

	/**
	 * 判断手机号是否合法
	 * 
	 * @param phoneNumber
	 * @return
	 */
	public static boolean isLegalPhoneNumber(String phoneNumber) {
		if (null == phoneNumber) {
			throw new IllegalArgumentException("the phoneNumber can't be null");
		}
		Pattern p = Pattern
				.compile("^((13[0-9])|(15[^4,\\D])|(18[0,5-9]))\\d{8}$");
		Matcher m = p.matcher(phoneNumber);
		return m.matches();
	}

	static Pattern patternLocation = Pattern
			.compile("<location>([\\s\\S]*)</location>");

	/**
	 * 根据IP返回归属地.
	 * 
	 * @param ip
	 * @return
	 */
	public static String getPhoneLocation(String ip) {
		String location = "";
		try {
			location = getStringFromUrl(new URL(YAODAO_PHONE_LOCATION_API + ip));
		} catch (Throwable e) {
			e.printStackTrace();
		}
		Matcher matcher = patternLocation.matcher(location);
		while (matcher.find()) {
			location = matcher.group(1);
			break;
		}
		Log.d(TAG, " [getPhoneLocation] location = " + location);
		return location;
	}

	private static final String TAG = PhoneNumberUtil.class.getSimpleName();

	private static String getStringFromUrl(URL url) {
		String result = "";
		try {
			HttpURLConnection connection = (HttpURLConnection) url
					.openConnection();
			InputStream is = connection.getInputStream();
			int i;
			byte[] buffer = new byte[4096];
			while ((i = is.read(buffer)) != -1) {
				String reads = new String(buffer, 0, i, "gbk");
				result = result + reads;
			}
		} catch (IOException e) {
		}
		Log.d(TAG, " [getStringFromUrl] result = " + result);
		return result;
	}
}
